﻿using System.Linq.Expressions;

namespace OnHook.Common.Extension
{
    /// <summary>
    /// lamda表达式
    /// </summary>
    public static class ExpressionExtension
    {
        /// <summary>
        /// AND操作
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="left"></param>
        /// <param name="right"></param>
        /// <returns></returns>
        public static Expression<Func<T, bool>> And<T>(this Expression<Func<T, bool>> left,
         Expression<Func<T, bool>> right)
        {
            var invokedExpr = Expression.Invoke(right, left.Parameters.CastTo<Expression>());
            return Expression.Lambda<Func<T, bool>>
                  (Expression.And(left.Body, invokedExpr), left.Parameters);
        }

        /// <summary>
        /// OR操作
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="left"></param>
        /// <param name="right"></param>
        /// <returns></returns>
        public static Expression<Func<T, bool>> Or<T>(this Expression<Func<T, bool>> left,
         Expression<Func<T, bool>> right)
        {
            var invokedExpr = Expression.Invoke(right, left.Parameters.CastTo<Expression>());
            return Expression.Lambda<Func<T, bool>>
                  (Expression.Or(left.Body, invokedExpr), left.Parameters);
        }

        /// <summary>
        /// 取反操作
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="expre"></param>
        /// <returns></returns>
        public static Expression<Func<T, bool>> Not<T>(this Expression<Func<T, bool>> expre)
        {
            return Expression.Lambda<Func<T, bool>>(Expression.Not(expre));
        }
    }
}
